<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>联机模式</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
    <!--    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->
    <link rel="stylesheet" type="text/css" href="css/zzsc.css">
    <link rel="stylesheet" type="text/css" href="css/style2.css">

    <script src="js/jquery-3.5.1.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/wangEditor.min.js"></script>

    <script type="text/javascript">


    // const editor = new E( document.getElementById('div1') )
    //>>>>>>>>>>>>>>>>新增变量,轮到玩家
    let nowIsPlayer = true;

    let lastx = -123456789, lasty = -123456789;
    let computerPlayChessSign = true;
    //<<<<<<<<<<<<<<<<<

    // 棋手编号 0 ~ 3 (包含3)
    let piecesPlay = 0;
    //
    // 其他棋手的编号
    let otherFirstPlayer = 1;
    let otherSecondPlayer = 2;
    let otherThirdPlayer = 3;

    // 全局变量
    let piecesColor = ['r1', 'y1', 'b1', 'g1']; // 棋手所用棋子颜色标志
    let notPosition = ['r2', 'y2', 'b2', 'g2']; // 棋手在该区域不能下棋子标志
    let canPosition = ['r3', 'y3', 'b3', 'g3']; // 棋手可在该区域下棋子标志
    let color = ['red', 'yellow', 'blue', 'green'];
    let con; //棋子需要用到的数组
    let boxIndex; // 棋盘需要用到的数组
    // 以最中间的一个格子为中心，上下左右各含有几个棋子
    let leftNum;
    let rightNum;
    let upperNum;
    let lowerNum;
    let determine; // 标记哪些棋子被用了
    let choose = 0;// 聚焦的棋子
    let first = true; // 标记是否下的为第一步

    //电脑1,2,3
    //let

    // 屏幕的高和宽
    let scWidth = screen.width;
    let scHeight = screen.height;

    // 旋转、翻转需要用到的参数
    let angle1 = -1;
    let angle2 = 90;
    let angle3 = -1;

    // 棋盘参数
    let boxLength = 800;
    let gridLength = 40;



    //复盘
    var replay = new Array();
    var rnum = 0;
    var nownum = 0;

    var f = false;

    // //初始化电脑的棋子使用情况
    // window.onload = function() {
    //   initComputerUsed();
    // }

    $(function() {

        //初始化电脑的棋子使用情况
        // initComputerUsed();
        //websocket();
        // 初始化棋盘
        initChessBoard();
        // 初始化各玩家棋子参数
        // initChessPlay();
        // 在候选区画出棋子
        // drawChess();
        // 为每个在候选区的棋子添加点击事件，使其可以显示在展示区
        // candChessClick();
        // 展示区内的棋子添加操作
        // chessChangeOperating();

        //打印boxIndex
        printBoxIndex();
        //富文本编辑器设置
        const E = window.wangEditor
        const editor = new E('#toolbar-container', '#text-container')
        // // 或者 const editor = new E( document.getElementById('div1') )

        editor.config.menus=[
            // 'head',  // 标题
            // 'bold',  // 粗体
            // 'fontSize',  // 字号
            // 'fontName',  // 字体
            // 'italic',  // 斜体
            // 'underline',  // 下划线
            // 'strikeThrough',  // 删除线
            // 'foreColor',  // 文字颜色
            // 'backColor',  // 背景颜色
            // 'link',  // 插入链接
            // 'list',  // 列表
            // 'justify',  // 对齐方式
            // 'quote',  // 引用
            // 'emoticon',  // 表情
            // 'image',  // 插入图片
            // 'table',  // 表格
            // 'video',  // 插入视频
            'code',  // 插入代码
            'undo',  // 撤销
            // 'redo'  // 重复
        ];

        editor.create();



        websocket(editor);





        $('#send').click(function () {

            let context = editor.txt.html();
            let size = context.length;
            let a = context.substring(28,size - 19);

            let message = {
                "type": "code",
                "chessnum": chessnum,
                "code":a,
                "username": username,
                "confirm": confirm
            };
            try {
                webSocket.send(JSON.stringify(message));
            }catch (e){
                console.log(e);
            }

            // $.ajax({
            //     url: "http://localhost:8081/compile/getanswer",
            //     type: 'POST',
            //     dataType: 'json',
            //     contentType: "application/json;charset=utf-8;",
            //     data:JSON.stringify(message),
            //     success:function(data){
            //         console.log(data.answer);
            //
            //
            //     },
            //     error:function(e){
            //     }
            // });
        });
        // editor.highlight = hljs;




        $('#button6').click(function () {
            // var audio =$('#bm') ;//jQuery对象
            // var au=audio.get(0); //DOM对象
            // au.play();
            if(nownum > 0){
                nownum--;
                console.log(rnum)
                console.log(nownum)
                drawChessBoard(replay[nownum]);
            }else {
                drawChessBoard(replay[nownum]);
            }
        });
        $('#button7').click(function () {
            // var audio =$('#bm') ;//jQuery对象
            // var au=audio.get(0); //DOM对象
            // au.play();
            if(nownum < rnum-1){
                nownum++;
                console.log(rnum)
                console.log(nownum)
                drawChessBoard(replay[nownum]);
            }else {
                drawChessBoard(replay[nownum]);
            }
        });

    })

    // 初始化棋盘
    function initChessBoard() {
        // 棋盘尺寸 20 * 20
        let boardSize = 20 * 20;
        let grid = '';
        for (let i = 0; i < boardSize; i++) {
            grid += '<div class="grid' + (i + 1) + '"></div>';
        }
        $('.chess-board').html(grid);
        boxIndex = new Array();
        for (let i = 0; i < 21; i++) {
            boxIndex[i] = new Array();
            for (let j = 0; j < 21; j++) {
                boxIndex[i][j] = 0;
            }
        }
        boxIndex[20][1] = 'r3';
        boxIndex[20][20] = 'y3';
        boxIndex[1][20] = 'b3';
        boxIndex[1][1] = 'g3';
    }

    //打印boxIndex二维数组
    function printBoxIndex() {
        console.log(boxIndex)
    }



    // 画出棋子
    function drawChess() {
        for (let i = 1; i <= 21; ++i) {
            $('.chess-place').append('<div class="chess-container' + i + '"></div>');
            $('.chess-container' + i).css({
                'width': 100 + 'px',
                'height': 100 + 'px',
                'margin': 5 + 'px',
                'display': 'block'
            });
            for (let j = 2; j <= 6; ++j) {
                for (let k = 2; k <= 6; ++k) {
                    if (con[i][j][k] !== piecesColor[piecesPlay]) {
                        $('.chess-container' + i).append('<div style="visibility: hidden;"></div>');
                    } else {
                        $('.chess-container' + i).append('<div class="drag' + i + '"></div>');
                        $('.drag' + i).css({
                            'outline': '1px solid #ffffff',
                            'cursor': 'pointer',
                            'background-color': color[piecesPlay]
                        });
                    }
                }
            }
            $('.chess-container' + i + ' div').css({
                'width': 20 + 'px',
                'height': 20 + 'px'
            });
        }
    }













    // 渲染棋盘
    function drawChessBoard(boxIndex) {
        for (let i = 1; i <= 20; ++i) {
            for (let j = 1; j <= 20; ++j) {
                let k = (i - 1) * 20 + j;

                if (boxIndex[i][j] === 'r1') {
                    $('.grid' + k).css('background-color', 'red');
                }
                if (boxIndex[i][j] === 'y1') {
                    $('.grid' + k).css('background-color', 'yellow');
                }
                if (boxIndex[i][j] === 'b1') {
                    $('.grid' + k).css('background-color', 'blue');
                }
                if (boxIndex[i][j] === 'g1') {
                    $('.grid' + k).css('background-color', 'green');
                }

                if(boxIndex[i][j] != 'r1' && boxIndex[i][j] != 'y1' && boxIndex[i][j] != 'b1' && boxIndex[i][j] != 'g1')
                    $('.grid' + k).css('background-color', '');

            }
        }
    }

    //棋局人数
    var peoplenum;
    //判断是否能下
    var flag = true;
    //弃权人数
    var abandon = 0;
    //棋局号
    var chessnum = 0;
    //棋手号
    var playernum;
    //当前下棋的人的棋手号
    var nowplayer = 0;
    //提交代码人数
    var confirm = 0;

    var s = sessionStorage.getItem("player");
    var username = s;
    // alert(s);
    $(".welcome").text("欢迎："+s);

    var webSocket;
    var commWebSocket;

    function websocket(editor) {

        if ("WebSocket" in window) {
            webSocket = new WebSocket("ws://localhost:8081/websocket3/"+s);

            //连通之后的回调事件
            webSocket.onopen = function()
            {
                //webSocket.send( document.getElementById('username').value+"已经上线了");
                console.log("已经连通了websocket");
                setMessageInnerHTML("已经连通了websocket");
            };

            //接收后台服务端的消息
            webSocket.onmessage = function (evt)
            {
                var received_msg = evt.data;
                console.log("数据已接收:" +received_msg);
                var obj = JSON.parse(received_msg);
                console.log("可以解析成json:"+obj.messageType);
                //1代表自己上线 获取其他选手名单 2代表下线 3接受棋局 4代表普通消息 5 其他人上线
                if(obj.messageType==1){
                    //人数
                    peoplenum = obj.num;
                    //棋局号
                    chessnum = obj.cn;
                    console.log("棋局号"+chessnum);
                    //棋手号
                    playernum = obj.playernum;
                    console.log("棋手号"+playernum);

                    if(playernum == 0){
                        editor.txt.html('<pre type="Java"><code><xmp>' +
                            'private static int[] computerPlay1(int no, int[] a) {' +'\n'+
                            '}'+
                            '</xmp></code></pre>');
                    }else if (playernum == 1){
                        editor.txt.html('<pre type="Java"><code><xmp>' +
                            'private static int[] computerPlay2(int no, int[] a) {' +
                            '}'+
                            '</xmp></code></pre>');
                    }else if (playernum == 2){
                        editor.txt.html('<pre type="Java"><code><xmp>' +
                            'private static int[] computerPlay3(int no, int[] a) {' +
                            '}'+
                            '</xmp></code></pre>');
                    }else if (playernum == 3){
                        editor.txt.html('<pre type="Java"><code><xmp>' +
                            'private static int[] computerPlay4(int no, int[] a) {' +
                            '}'+
                            '</xmp></code></pre>');
                    }


                    var onlineName = obj.onlineUsers;
                    var option = null;
                    for(var i=0;i<onlineName.length;i++){
                        if(!(onlineName[i]==s)){
                            option+="<option>"+onlineName[i]+"</option>"
                        }
                    }
                    $("#onLineUser").append(option);
                    console.log("获取了在线的名单"+onlineName.toString());


                }
                else if(obj.messageType==2){
                    $("#onLineUser").empty();
                    var onlineName = obj.onlineUsers;
                    var offlineName = obj.username;
                    var option = "<option>"+"--所有--"+"</option>";
                    for(let i=0;i<onlineName.size;i++){
                        if(!(onlineName[i]==username)){
                            option+="<option>"+onlineName[i]+"</option>"
                        }
                    }
                    $("#onLineUser").append(option);

                    setMessageInnerHTML(offlineName+"下线了");
                }
                else if(obj.messageType==3){
                    confirm = obj.confirm;
                    if(confirm == 4){
                        let cb = obj.chessBoard;
                        let a = [];
                        a = cb.split("|");
                        let num = 0;

                        for(let l = 0; l < a.length; l++){
                            replay[l] = new Array();
                            let split = [];
                            split = a[l].split("#");
                            for(let r = 0; r < split.length; r++){
                                replay[l][r] = new Array();
                                let x = [];
                                x = split[r].split(",");
                                for(let j = 0; j < x.length; j++){
                                    replay[l][r][j] = x[j];
                                }
                            }
                            num++;
                        }
                        console.log(replay);
                        alert("编译完成");
                        winner(replay[num-1]);
                        drawChessBoard(replay[num-1]);
                        rnum = num;
                        nownum = num-1;
                    }


                }
                else if(obj.messageType==4){
                    setMessageInnerHTML(obj.fromusername+"对"+obj.tousername+"说："+obj.textMessage);
                }else if(obj.messageType==5){
                    //人数
                    num = obj.num;
                    //把名称放入到selection当中供选择
                    var onlineName = obj.username;
                    var option = "<option>"+onlineName+"</option>";
                    $("#onLineUser").append(option);
                    setMessageInnerHTML(onlineName+"上线了");


                }else if (obj.messageType==6){
                    setMessageInnerHTML(obj.username+" 已经提交代码");
                }
            };
            //连接关闭的回调事件
            webSocket.onclose = function(e)
            {
                console.log(e)
                console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)

                console.log("连接已关闭...");
                setMessageInnerHTML("连接已经关闭....");
            };
        }
        else{
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }

    function winner(chessboard) {
        let num = new Array();
        num[0] = 0;
        num[1] = 0;
        num[2] = 0;
        num[3] = 0;
        for(let i = 0; i < chessboard.length;i++){
            for(let j = 0; j < chessboard[i].length;j++){
                if(chessboard[i][j] == "r1"){
                    num[0]+=1;
                }else if (chessboard[i][j] == "y1"){
                    num[1]+=1;
                }else if (chessboard[i][j] == "b1"){
                    num[2]+=1;
                }else if (chessboard[i][j] == "g1"){
                    num[3]+=1;
                }
            }
        }
        let max = num[0];
        let win = 0;
        for(let i = 1; i < num.length; i++){
            if(num[i] > max){
                max = num[i];
                win = i;
            }
        }
        if(win == 0){
            alert("红色棋子数: "+num[0]+"\n"+"黄色棋子数: "+num[1]+"\n"+"蓝色棋子数: "+num[2]+"\n"+"绿色棋子数: "+num[3]+"\n"+"胜利者为: 红色");

        }else if(win == 1){
            alert("红色棋子数: "+num[0]+"\n"+"黄色棋子数: "+num[1]+"\n"+"蓝色棋子数: "+num[2]+"\n"+"绿色棋子数: "+num[3]+"\n"+"胜利者为: 黄色");
        }else if(win == 2){
            alert("红色棋子数: "+num[0]+"\n"+"黄色棋子数: "+num[1]+"\n"+"蓝色棋子数: "+num[2]+"\n"+"绿色棋子数: "+num[3]+"\n"+"胜利者为: 蓝色");
        }else if(win == 3){
            alert("红色棋子数: "+num[0]+"\n"+"黄色棋子数: "+num[1]+"\n"+"蓝色棋子数: "+num[2]+"\n"+"绿色棋子数: "+num[3]+"\n"+"胜利者为: 绿色");
        }

    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    function closeWebSocket() {
        //直接关闭websocket的连接
        webSocket.close();
    }





    function sendMessage() {
        var selectText = $("#onLineUser").find("option:selected").text();
        if(selectText=="--所有--"){
            selectText = "All";
        }
        else{
            setMessageInnerHTML(username+"对"+selectText+"说："+ $("#text").val());
        }
        var message = {
            "type": "message",
            "chessnum": chessnum,
            "message":document.getElementById('text').value,
            "username": username,
            "to":selectText
        };
        webSocket.send(JSON.stringify(message));
        $("#text").val("");

    }

    function mychange() {
        if(f == true){
            $("#explain").css("display", "none");
            f = false;
        }else{
            $("#explain").css("display", "inline-block");
            f = true;
        }

    }


    </script>

</head>
<body>
<audio preload="auto"  id="bm">
    <source src="music/button02a.mp3" type="audio/mpeg">
    您的浏览器不支持 audio 元素。
</audio>

<div id="chat" style=" border:1px solid black; padding: 10px; margin: 5px;width: 300px;height: 600px; position:absolute; top: 50px;
left: 150px; background: #1cbbb4;
            border-width: 0.02rem .02rem .02rem .02rem;
            border-radius: .5rem .5rem .5rem .5rem;">
<!--    -->
    <br/>
    <div style="margin: auto;text-align: center">
        <select id="onLineUser">
            <option>--所有--</option>
        </select>
        <input id="text" type="text" />
        <button class="btn btn-primary btn-lg" onclick="sendMessage()">发送消息</button>
        <button class="btn btn-primary btn-lg" onclick="closeWebSocket()">关闭连接</button>
    </div>
    <br>

    <hr/>
    <div id="message" style="text-align: center; position: absolute; left: 80px; top: 100px"></div>
    <input  type="text"  id="username" style="display: none" />

<!--    <div style="margin-right: 10px;text-align: right">-->

<!--    </div>-->
</div>

<!--<div class="candidate" id="chplace">-->
<!--  <div class="chess-place"></div>-->
<!--  <div style="position: absolute; left: 160px; bottom: -55px">-->
<!--    <button type="button" class="btn btn-primary btn-lg" id="button5" >永久跳过</button>-->
<!--  </div>-->
<!--</div>-->
<div style="position: absolute; right: 25px; top: 25px;" >
    <button type="button" class="btn btn-primary btn-lg" id="button8" style="z-index: 99999"  onclick="mychange()">说明</button>
</div>
<div id="explain" style="position: absolute; top: 50px; left: 750px;background: white; z-index: 99999; display: none; background: lightyellow;
border-width: 0.02rem .02rem .02rem .02rem;
            border-style: solid;
            border-radius: .35rem .35rem .35rem .35rem;">

    <p style="margin-left: 10px"><br><br>
        在右边传入代码后点击上传，就能将代码传入后端。<br><br>
        之后一局的四个人都上传代码后就会进行编译。<br><br>
        编译完成后就会显示结果，以及整个棋局。<br><br>
        得到棋局后可以通过左边的上一步、下一步进行复盘。<br><br>
        <br><br>
        介绍棋局所用变量
        <br><br>
        棋盘是由21X21的字符串数组构成，只使用了1到20这20个位置，0位没有使用。<br><br>
        static String[][] boxIndex = new String[21][21];<br><br>
        <br><br>
        这个是装棋子用的数组，一共有21个棋子。每个棋子都用8X8的数组组成。<br><br>
        在这个数组中棋子占据的地方设置为r1、y1、b1、g1，具体是那个，由棋手的棋号决定。<br><br>
        static String[][][] con = new String[22][8][8];<br><br>
        <br><br>
        当决定下棋的时候请将con数组中对应的值填入<br><br>
        <br><br>
        这个是上传代码的样子，<strong>需要跟右侧的代码框架一样</strong>，如果传错就会无法显示。<br><br>
        private static int[] computerPlay1(int no, int[] a) {<br><br>
        <br><br>
        }<br><br>
        这个里面传入的变量no是指棋手编号，从0到3，分别代表红色，黄色，蓝色，绿色这四种颜色。<br><br>
        a是一个a[4]数组，当决定不下的时候请将a[no]设置为1，否则可能进入死循环无法得到结果。<br><br>
        <br><br>
        棋手所用棋子颜色标志<br><br>
        static String piecesColor[] = {"r1", "y1", "b1", "g1"};<br><br>
        <br><br>
        棋手在该区域不能下棋子标志<br><br>
        static String notPosition[] = {"r2", "y2", "b2", "g2"};<br><br>
        <br><br>
        棋手可在该区域下棋子标志<br><br>
        static String canPosition[] = {"r3", "y3", "b3", "g3"};<br><br>
        <br><br>
        标记哪些棋子被用了<br><br>
        static boolean[] determine = new boolean[22];<br><br>
        <br><br>
    </p>
</div>
<div id="compile" style="position: absolute; width: 500px; height: 650px; z-index: 9; right: 25px; top: 75px;">
    <!--  <p>输入代码</p>-->
    <div id="toolbar-container" class="toolbar"></div>

    <div id="text-container" style="width:500px; height:750px; background: #1cbbb4;border-width: 0.02rem .02rem .02rem .02rem;
            border-radius: .5rem .5rem .5rem .5rem;" class="text">

    </div>
    <button id="send" class="btn btn-primary btn-lg" >发送</button>
</div>


<div class="box">
    <div class="chess-board"></div>
    <div class="chess-confirm">
        <!--    <button type="button" class="btn btn-primary btn-lg" id="button4">确定</button>-->
    </div>

</div>

<!--<div class="exhibition" id="mychange">-->
<!--  <div class="exhi-content"></div>-->
<!--  <div class="exhi-operate">-->
<!--    <button type="button" class="btn btn-primary btn-lg" id="button1">左右翻转</button>-->
<!--    <button type="button" class="btn btn-primary btn-lg" id="button2">旋转</button>-->
<!--    <button type="button" class="btn btn-primary btn-lg" id="button3">上下翻转</button>-->
<!--  </div>-->
<!--</div>-->
<div style="position: absolute; left: 200px; bottom: 150px; display: inline-block" id="rebutton">

    <button type="button" class="btn btn-primary btn-lg" id="button6" >上一步</button>
    <button type="button" class="btn btn-primary btn-lg" id="button7" >下一步</button>
</div>
</body>
</html>
